<template>
  <div class="flex flex-col h-full">
    <!--    <vxe-card title="" class="w-full" :border="false">-->
    <!--      <div class="flex items-center">-->
    <!--        <div class="border-arrow" @click="toPrevPage">-->
    <!--          <FontIcon icon="icon-left" />-->
    <!--        </div>-->
    <!--        <div class="text-[#242930] ml-4">-->
    <!--          <span class="text-[&#45;&#45;autata-font-gray-color]">配方列表：</span>-->
    <!--          {{ getParameter.name }}-->
    <!--        </div>-->
    <!--      </div>-->
    <!--    </vxe-card>-->

    <vxe-card title="" class="w-full" :border="false">
      <AuForm
        ref="formRef"
        :formList="formList"
        :exportBtnFlag="false"
        @exportPdf="exportTemplate"
        @submit="search"
      />
    </vxe-card>

    <AuTable
      ref="tableRef"
      v-bind="gridOption"
      class="mt-[16px]"
      @actionClick="actionClick"
    >
      <template #topWrap>
        <div class="text-[#242930]">
          <span class="text-[--autata-font-gray-color]"
            >{{ t("formula.version.formula_list") }}：</span
          >
          {{ getParameter.name }}
        </div>
      </template>
      <template #status_default="{ row }">
        <el-tag :type="row.publishStatus ? 'success' : 'info'"
          >{{
            row.publishStatus
              ? t("formula.version.status_up")
              : t("formula.version.status_down")
          }}
        </el-tag>
      </template>
    </AuTable>
    <FormulaDetailModal
      v-model:showModal="showDetailModal"
      :rowData="rowData"
      :versionId="versionId"
      @handleConfirm="handleConfirm"
    />

    <UploadModal
      v-model="showUploadModal"
      :versionId="versionId"
      :tableData="tableData"
      @handleConfirm="handleUploadConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { AuForm } from "@/components/AuForm";
import { AuTable } from "@/components/AuTable";
import { ACTION_TYPE, PropDefines } from "@/components/AuTable/type";
import {
  delFormula,
  FormulaListProp,
  getFormulaList,
  updatePublishFormula
} from "@/api/teaInfuser/formula";
import FormulaDetailModal from "./FormulaDetailModal.vue";
import { useDetail } from "../hooks";
import { GetListParamProp } from "@/api/user";
import { ElMessage, ElMessageBox } from "element-plus";
import { onBeforeRouteLeave, useRouter } from "vue-router";
import { useGlobal } from "@pureadmin/utils";
import UploadModal from "@/views/teaInfuser/formula/formulaDetail/uploadModal.vue";
import { getFormulaDetail } from "@/api/teaInfuser/formula";
import ExcelJS from "exceljs"; // 引入exceljs, 用于生成excel文件
import { saveAs } from "file-saver";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

defineOptions({
  name: "FormulaDetail"
});

const emit = defineEmits(["update:showModal"]);
const { initToDetail, getParameter } = useDetail();
initToDetail("query");
const { proxy } = getCurrentInstance();

// region 页面及组件变量集合
const { $storage } = useGlobal<GlobalPropertiesApi>();
const router = useRouter();

const showUploadModal = ref(false);
const tableData = ref<object[]>([]);

const formList = ref([
  {
    type: "input",
    key: "name",
    label: "formula.version.name",
    labelWidth: "40px",
    placeholder: "formula.version.name_placeholder"
  },
  {
    type: "select",
    key: "publishStatus",
    label: "formula.version.status",
    placeholder: "formula.version.status_placeholder",
    labelKey: "label",
    valueKey: "value",
    columns: [],
    options: [
      {
        value: 0,
        label: "formula.version.status_down"
      },
      {
        value: 1,
        label: "formula.version.status_up"
      }
    ]
  }
]);

const showDetailModal = ref(false);
const gridOption = reactive<PropDefines>({
  isServerPage: true,
  showCheckbox: true,
  columns: [
    { field: "formulaId", title: "formula.version.id" },
    { field: "name", title: "formula.version.name" },
    {
      field: "publishStatus",
      title: "formula.version.status",
      slots: { default: "status_default" }
    },
    { field: "updateTime", title: "formula.version.publish_time", width: 190 }
  ],
  actions: [
    ACTION_TYPE.TADD,
    ACTION_TYPE.UPLOAD,
    ACTION_TYPE.EDIT,
    ACTION_TYPE.DOWNLOAD,
    ACTION_TYPE.TDELETE
  ],
  operateTools: [
    {
      name: "table.putaway",
      key: "putaway",
      seq: 11,
      hiddenHandle: (row: FormulaListProp) => {
        return row.publishStatus === 1;
      }
    },
    {
      name: "table.soldOut",
      key: "soldOut",
      seq: 12,
      hiddenHandle: (row: FormulaListProp) => {
        return row.publishStatus === 0;
      }
    }
  ],
  dataSource: [],
  fetchConfig: {
    query: {
      service: (
        params: GetListParamProp<{ version: string; hxtFormula: object }>
      ) => {
        const { start_page, size, ...rest } = params;
        params = {
          start_page: start_page ?? 1,
          size: size ?? 0,
          hxtFormula: rest
        };

        return getFormulaList(params);
      },
      param: () => {
        return {
          version: Number(getParameter["id"]),
          ...formRef.value.getFormData()
        };
      }
    }
  }
});
const rowData = ref({});
const versionId = ref(getParameter["id"] as string);

const formRef = ref();
const tableRef = ref();
// endregion

// region 页面公共方法集合
function storageConfigureChange<T>(key: string, val: T): void {
  const storageConfigure = $storage.configure;
  storageConfigure[key] = val;
  // $storage.configure = storageConfigure;
}

const multiDelete = () => {
  if (!tableRef.value.getCheckboxRecords().length) {
    ElMessage({
      message: t("formula.version.select_delete"),
      type: "warning"
    });
    return;
  }
  proxy.$auMessageBox
    .confirm(t("formula.version.delete_confirm"), t("notice.title"), {
      type: "warning"
    })
    .then(() => {
      const formulaIds = tableRef.value
        .getCheckboxRecords()
        .map((v: FormulaListProp) => v.formulaId);
      delFormula({ formulaIds }).then(res => {
        ElMessage({
          message: t("notice.operation_success"),
          type: "success"
        });
        tableRef.value.refresh();
      });
    });
};
// endregion

// region 页面及组件事件集合
const toPrevPage = () => {
  router.go(-1);
};

const search = () => {
  // console.log(data);
  tableRef.value.refresh();
};

const actionClick = ({
  key,
  row
}: {
  key: ACTION_TYPE | string;
  row: FormulaListProp;
}) => {
  switch (key) {
    case ACTION_TYPE.TADD:
    case ACTION_TYPE.EDIT:
      rowData.value = row;
      showDetailModal.value = true;
      break;
    case ACTION_TYPE.TDELETE:
      multiDelete();
      break;
    case "putaway":
    case "soldOut":
      proxy.$auMessageBox
        .confirm(
          t("formula.version.status_change_confirm", {
            status:
              key === "putaway"
                ? t("formula.version.status_up")
                : t("formula.version.status_down"),
            name: row.name
          }),
          t("notice.title"),
          {
            type: "warning"
          }
        )
        .then(() => {
          updatePublishFormula({
            formulaId: row.formulaId,
            publishStatus: key === "putaway" ? 1 : 0
          }).then(res => {
            if (res.code === 200) {
              ElMessage({
                message: t("notice.operation_success"),
                type: "success"
              });
              tableRef.value.refresh();
            }
          });
        });
      break;
    case ACTION_TYPE.UPLOAD:
      console.log("打开配方导入页面");
      getFormulaList({
        size: 0,
        start_page: 1,
        hxtFormula: { version: versionId.value }
      }).then(res => {
        tableData.value = res.data;
        showUploadModal.value = true;
      });
      break;
    case ACTION_TYPE.DOWNLOAD:
      exportTemplate();
      break;
    default:
      break;
  }
};

const handleConfirm = () => {
  tableRef.value.refresh();
};

//导入
const handleUploadConfirm = () => {
  console.log("开始配方导入");
  showUploadModal.value = false;
  tableRef.value.refresh();
};

//暂未用，待完善
const setCellDetail = async (worksheet, cell, value) => {};

//设置填充色
const setFill = async (
  worksheet,
  rowNumber,
  startColIndex,
  endColIndex,
  fillStyle
) => {
  if (rowNumber % 2 == 0) {
    for (let colIndex = startColIndex; colIndex <= endColIndex; colIndex++) {
      const cell = worksheet.getCell(rowNumber, colIndex);
      cell.fill = fillStyle;
    }
  }
};

//导出配方
const exportTemplate = async () => {
  console.log("开始导出配方");

  //获取配方列表
  const hxtFormulaParam = await getParams();

  const params = {
    start_page: 1,
    size: 0,
    hxtFormula: hxtFormulaParam
  };

  let pfResult = await getFormulaList(params); //获取配方列表
  if (pfResult.code == 200 && pfResult.data.length > 0) {
    const pfList = pfResult.data;
    /* const workbook = new ExcelJS.Workbook(); // 创建工作簿

    const worksheet = workbook.addWorksheet("配方"); // 添加工作表 */

    // 获取模板文件
    const response = await fetch("/admin/配方导出模板.xlsx");
    const arrayBuffer = await response.arrayBuffer();

    // 创建工作簿
    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.load(arrayBuffer);

    // 获取第一个工作表
    const worksheet = workbook.getWorksheet(1);

    //模板边框样式
    const cellExample = worksheet.getRow(2).getCell(1);
    const cellExampleStyle = {
      top: { ...cellExample.border.top },
      left: { ...cellExample.border.left },
      bottom: { ...cellExample.border.bottom },
      right: { ...cellExample.border.right }
    };
    //模板填充样式
    const cellFillExampleStyle = cellExample.fill;

    //获取颜色
    // console.log(worksheet.getRow(2).getCell(1).border.top);
    // const borderColors = await getBorderColors(worksheet.getRow(2).getCell(1));

    const space = 9;

    for (let pfIndex = 0; pfIndex < pfList.length; pfIndex++) {
      //获取配方详情
      const formulaResult = await getFormulaDetail({
        formulaId: pfList[pfIndex].formulaId
      });

      const formulaDetail = formulaResult.data;

      setFill(
        worksheet,
        2,
        1 + pfIndex * space,
        8 + pfIndex * space,
        cellFillExampleStyle
      );
      worksheet.getRow(2).getCell(1 + pfIndex * space).value = "*配方名称"; //设置配方名称title

      worksheet.mergeCells(2, 2 + pfIndex * space, 2, 2 + pfIndex * space + 6); //合并单元格

      worksheet.getRow(2).getCell(2 + pfIndex * space).value =
        formulaDetail.hxtFormula.name; //设置配方名称
      worksheet.getColumn(2 + pfIndex * space).width = 15;
      worksheet.getRow(3).getCell(1 + pfIndex * space).value = "配方分类"; //设置配方分类title

      worksheet.getColumn(3 + pfIndex * space).width = 15;

      const pftype = formulaDetail.hxtFormula.type;
      let pffl = "";
      if (pftype == 2) {
        pffl = "红茶";
      } else if (pftype == 1) {
        pffl = "绿茶";
      }
      worksheet.getRow(3).getCell(2 + pfIndex * space).value = pffl; //设置配方名分类
      worksheet.getColumn(2 + pfIndex * space).width = 15;

      worksheet.getRow(3).getCell(3 + pfIndex * space).value = "外部id"; //设置外部id title

      worksheet.getRow(3).getCell(4 + pfIndex * space).value =
        formulaDetail.hxtFormula.thirdValue; //设置外部id

      worksheet.getRow(3).getCell(5 + pfIndex * space).value = "无盖泡茶桶"; //设置无盖泡茶桶 title
      worksheet.getColumn(5 + pfIndex * space).width = 18;
      const wgpct = formulaDetail.hxtFormula.switchNoCheck;
      let wgpctms = "";
      if (wgpct == 0) {
        wgpctms = "否";
      } else if (wgpct == 1) {
        wgpctms = "是";
      }
      worksheet.getRow(3).getCell(6 + pfIndex * space).value = wgpctms; //设置无盖泡茶桶

      worksheet.getRow(3).getCell(7 + pfIndex * space).value = "进水搅拌开关"; //设置 title
      worksheet.getColumn(7 + pfIndex * space).width = 18;
      const jbInWater = formulaDetail.hxtFormula.jbInWater;
      let jbInWaterText = "";
      if (jbInWater == 0) {
        jbInWaterText = "关";
      } else if (jbInWater == 1) {
        jbInWaterText = "开";
      }
      worksheet.getRow(3).getCell(8 + pfIndex * space).value = jbInWaterText; //设置无盖泡茶桶

      //处理该规格
      //根据规格数处理数据worksheet.mergeCells(rowIndex, startColumnIndex, rowIndex, endColumnIndex)
      const hxtFormulaSpecDetailList = formulaDetail.hxtFormulaSpecDetailList;
      let specRowIndex = 4;
      if (
        hxtFormulaSpecDetailList != null &&
        hxtFormulaSpecDetailList.length > 0
      ) {
        let n = 0; //规格行数计数
        //规格存在才处理
        for (
          let ggIndex = 0;
          ggIndex < hxtFormulaSpecDetailList.length;
          ggIndex++
        ) {
          n++;
          specRowIndex++;
          worksheet.mergeCells(
            3 + n,
            1 + pfIndex * space,
            3 + n,
            6 + pfIndex * space
          ); //合并单元格
          setFill(
            worksheet,
            3 + n,
            1 + pfIndex * space,
            8 + pfIndex * space,
            cellFillExampleStyle
          );
          n++;
          specRowIndex++;
          setFill(
            worksheet,
            3 + n,
            1 + pfIndex * space,
            8 + pfIndex * space,
            cellFillExampleStyle
          );
          worksheet.getRow(3 + n).getCell(1 + pfIndex * space).value =
            "规格名称"; //设置规格名称 title
          worksheet.getRow(3 + n).getCell(2 + pfIndex * space).value =
            hxtFormulaSpecDetailList[ggIndex].specName; //设置规格名称
          worksheet.getRow(3 + n).getCell(3 + pfIndex * space).value = "外部id"; //设置外部id title
          worksheet.getRow(3 + n).getCell(4 + pfIndex * space).value =
            hxtFormulaSpecDetailList[ggIndex].thirdValue; //设置外部id
          worksheet.getRow(3 + n).getCell(5 + pfIndex * space).value = "茶叶量"; //茶叶量 title
          worksheet.getRow(3 + n).getCell(6 + pfIndex * space).value =
            hxtFormulaSpecDetailList[ggIndex].materialW; //设置茶叶量

          //设置分段表头
          n++;
          specRowIndex++;
          setFill(
            worksheet,
            3 + n,
            1 + pfIndex * space,
            8 + pfIndex * space,
            cellFillExampleStyle
          );
          worksheet.getRow(3 + n).getCell(1 + pfIndex * space).value = "分段"; //设置分段 title
          worksheet.getRow(3 + n).getCell(2 + pfIndex * space).value =
            "*进水量(ml)"; //设置进水量(ml) title
          worksheet.getRow(3 + n).getCell(3 + pfIndex * space).value =
            "*温度(°C)"; //设置温度(°C) title
          worksheet.getRow(3 + n).getCell(4 + pfIndex * space).value =
            "*泡茶时间(S)"; //设置泡茶时间(S) title
          worksheet.getRow(3 + n).getCell(5 + pfIndex * space).value =
            "搅拌时间(S)"; //设置搅拌时间(S) title
          worksheet.getRow(3 + n).getCell(6 + pfIndex * space).value =
            "冰块(g)"; //设置冰块(g) title
          worksheet.getRow(3 + n).getCell(7 + pfIndex * space).value =
            "出茶时间(s)"; //设置冰块(g) title
          //循环插入分段
          const hxtFormulaDetailList =
            hxtFormulaSpecDetailList[ggIndex].hxtFormulaDetailList;
          if (hxtFormulaDetailList != null && hxtFormulaDetailList.length > 0) {
            for (
              let fdIndex = 0;
              fdIndex < hxtFormulaDetailList.length;
              fdIndex++
            ) {
              n++;
              specRowIndex++;
              setFill(
                worksheet,
                3 + n,
                1 + pfIndex * space,
                8 + pfIndex * space,
                cellFillExampleStyle
              );
              worksheet.getRow(3 + n).getCell(1 + pfIndex * space).value =
                "第" + (fdIndex + 1) + "段";
              worksheet.getRow(3 + n).getCell(2 + pfIndex * space).value =
                Number(hxtFormulaDetailList[fdIndex].waterValue);
              worksheet.getRow(3 + n).getCell(3 + pfIndex * space).value =
                Number(hxtFormulaDetailList[fdIndex].temp);
              worksheet.getRow(3 + n).getCell(4 + pfIndex * space).value =
                Number(hxtFormulaDetailList[fdIndex].time);

              //处理搅拌时间
              const detail = hxtFormulaDetailList[fdIndex].detail;
              let jbsj = "";
              if (detail != null && detail != "[]") {
                const jsonData = JSON.parse(detail);
                jbsj = jsonData
                  .map(
                    item =>
                      `${item.begin}-${Number(item.begin) + Number(item.time)}`
                  )
                  .join(",");
                worksheet.getRow(3 + n).getCell(5 + pfIndex * space).value =
                  jbsj;
              } else {
              }

              worksheet.getRow(3 + n).getCell(6 + pfIndex * space).value =
                Number(hxtFormulaDetailList[fdIndex].iceWeight);

              const timeTeaOut = hxtFormulaDetailList[fdIndex]
                ?.timeTeaOut as any;
              const outTea = timeTeaOut ? timeTeaOut / 1000 : "";
              worksheet.getRow(3 + n).getCell(7 + pfIndex * space).value =
                outTea ?? "";
            }
          }
        }

        for (let bi = 1; bi < space; bi++) {
          for (let rowi = 2; rowi < specRowIndex; rowi++) {
            worksheet.getRow(rowi).getCell(bi + pfIndex * space).border =
              cellExampleStyle; //设置边框样式
            console.log(bi + pfIndex * space, bi, rowi);
          }
        }
      }
    }
    //导出
    workbook.xlsx.writeBuffer().then(function (buffer) {
      // 生成excel文件的二进制数据
      saveAs.saveAs(
        new Blob([buffer], {
          // 生成Blob对象
          type: "application/octet-stream" // 指定文件的MIME类型
        }),
        "配方数据.xlsx"
      ); // 指定文件名
    });
  } else {
    ElMessage({
      message: t("formula.version.no_export"),
      type: "warning"
    });
  }
};

//获取导出参数
const getParams = () => {
  return {
    version: Number(getParameter["id"]),
    ...formRef.value.getFormData()
  };
};
// endregion

// onMounted(() => {
//   storageConfigureChange("hideTabs", true);
//   emitter.emit("tagViewsChange", true as unknown as string);
// });
//
// onBeforeRouteLeave((to, from, next) => {
//   storageConfigureChange("hideTabs", false);
//   emitter.emit("tagViewsChange", false as unknown as string);
//
//   next();
// });
</script>
